package org.example.studentmanager.controller;

import jakarta.validation.Valid;
import org.example.studentmanager.model.Student;
import org.example.studentmanager.repository.StudentRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/students")
public class StudentController {
    private static final Logger logger = LoggerFactory.getLogger(StudentController.class);

    @Autowired
    private StudentRepository studentRepository;

    @GetMapping
    public String listStudents(Model model, @RequestParam(required = false) String keyword) {
        List<Student> students;
        try {
            if (keyword != null && !keyword.isEmpty()) {
                students = studentRepository.findByNameContaining(keyword);
            } else {
                students = studentRepository.findAll();
            }
            // 确保students不会是null
            if (students == null) {
                students = new ArrayList<>();
            }
        } catch (Exception e) {
            students = new ArrayList<>();
            model.addAttribute("error", "加载学生列表失败: " + e.getMessage());
        }
        model.addAttribute("students", students);
        model.addAttribute("keyword", keyword);

        // 获取当前用户角色
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        boolean isAdmin = authentication.getAuthorities().stream()
                .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"));

        if (isAdmin) {
            return "index"; // 管理员返回原视图
        }
        return "user-view-students"; // 普通用户返回专用视图
    }

    // 显示添加学生表单
    @GetMapping("/new")
    public String showAddForm(Model model) {
        logger.info("Showing add student form");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            logger.info("User is not authenticated, redirecting to login");
            return "redirect:/login";
        }
        try {
            model.addAttribute("student", new Student());
        } catch (Exception e) {
            model.addAttribute("error", "初始化表单失败: " + e.getMessage());
            logger.error("Failed to initialize add student form", e);
        }
        return "add-student";
    }

    // 保存学生
    @PostMapping("")
    public String saveStudent(@Valid @ModelAttribute Student student,
                              BindingResult result,
                              Model model) {
        logger.info("Saving student: {}", student.getName());
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            logger.info("User is not authenticated, redirecting to login");
            return "redirect:/login";
        }
        if (result.hasErrors()) {
            logger.info("Validation errors found, returning add-student form");
            return "add-student";
        }
        try {
            studentRepository.save(student);
            logger.info("Student {} saved successfully", student.getName());
            return "redirect:/students";
        } catch (Exception e) {
            model.addAttribute("student", student);
            model.addAttribute("error", "保存学生信息失败: " + e.getMessage());
            logger.error("Failed to save student information", e);
            return "add-student";
        }
    }

    @ModelAttribute("departments")
    public List<String> getDepartments() {
        return Arrays.asList("计算机科学", "电子工程", "机械工程", "工商管理", "外语学院");
    }

    // 显示编辑表单
    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Long id, Model model) {
        logger.info("Showing edit student form for student id: {}", id);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            logger.info("User is not authenticated, redirecting to login");
            return "redirect:/login";
        }
        Student student = studentRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("无效的学生ID: " + id));
        model.addAttribute("student", student);
        return "edit-student";
    }

    // 更新学生
    @PostMapping("/update/{id}")
    public String updateStudent(@PathVariable Long id, @ModelAttribute("student") Student student, BindingResult result) {
        logger.info("Updating student with id: {}", id);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            logger.info("User is not authenticated, redirecting to login");
            return "redirect:/login";
        }
        if (result.hasErrors()) {
            logger.info("Validation errors found, returning edit-student form");
            return "edit-student";
        }
        student.setId(id);
        studentRepository.save(student);
        logger.info("Student with id {} updated successfully", id);
        return "redirect:/students";
    }

    // 删除学生
    @GetMapping("/delete/{id}")
    public String deleteStudent(@PathVariable Long id) {
        logger.info("Deleting student with id: {}", id);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            logger.info("User is not authenticated, redirecting to login");
            return "redirect:/login";
        }
        studentRepository.deleteById(id);
        logger.info("Student with id {} deleted successfully", id);
        return "redirect:/students";
    }

    // 查看学生详情
    @GetMapping("/view/{id}")
    public String viewStudent(@PathVariable Long id, Model model) {
        logger.info("Viewing student details for student id: {}", id);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            logger.info("User is not authenticated, redirecting to login");
            return "redirect:/login";
        }
        Student student = studentRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("无效的学生ID: " + id));
        model.addAttribute("student", student);
        return "view-student";
    }
}